package com.tticar.invmanager.tticar.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.plugins.Page;
import com.czy.tticar.dubbo.dto.StorageOrderSaveRequest;
import com.czy.tticar.dubbo.service.StorageStoreService;
import com.czy.tticar.service.common.PageList;
import com.czy.tticar.service.dubbodto.ReceiverAddrResponse;
import com.czy.tticar.service.dubbodto.StoreSearchDto;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.entity.MMaterielTticar;
import com.tticar.invmanager.entity.vo.GoodsSearchDTO;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.PlaceOrderDTO;
import com.tticar.invmanager.entity.vo.SkuReturnToPage;
import com.tticar.invmanager.mapper.MMaterielSkuMapper;
import com.tticar.invmanager.tticar.entity.Goods;
import com.tticar.invmanager.tticar.entity.GoodsProduction;
import com.tticar.invmanager.tticar.entity.GoodsTmp;
import com.tticar.invmanager.tticar.entity.Store;
import com.tticar.invmanager.tticar.mapper.GoodsMapper;
import com.tticar.invmanager.tticar.service.IGoodsService;
import com.tticar.invmanager.tticar.service.IStoreService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yandou on 2018/7/24.
 */
@Controller
@RequestMapping("tticar")
public class TTicarController {

    @Autowired
    private IStoreService storeService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private MMaterielSkuMapper materielMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StorageStoreService storageStoreService;
    @Autowired
    private MMaterielSkuMapper materielSkuMapper;

    /**
     * @param page
     * @param ptype
     * @param storeId
     * @return
     */
    @RequestMapping("pushlet")
    @ResponseBody
    public Page pushlet(Page page, String ptype, Long storeId) {
        return storeService.pushlet(page, ptype, storeId);
    }

    @GetMapping("order")
    public String orders(MMaterielTticar mMaterielTticar, ModelMap modelMap) {
        modelMap.put("id", mMaterielTticar.getId());
        return "/tticar/mMaterielTticar/mMaterielTticar_edit";
    }

    @GetMapping("goods")
    public String edit(MMaterielTticar mMaterielTticar, ModelMap modelMap) {
        //根据天天爱车id查询 出存货id

        modelMap.put("id", mMaterielTticar.getId());
        return "/tticar/mMaterielTticar/mMaterielTticar_edit";
    }


    /**
     * 编辑取出产品信息
     * */
    @GetMapping("goods/{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        Map goodsMessageById = goodsService.getById(id);
        List<GoodsProduction> skus = (List) goodsMessageById.get("skus");
        for (int i = 0; i< skus.size();i++) {
            String skuId = String.valueOf(skus.get(i).getSkuId());
            String goodsId = String.valueOf(skus.get(i).getGoodId());
            skus.get(i).setGoodsIdString(goodsId);
            Map map = materielSkuMapper.querySkuIdByTticarGoodsSkuId(goodsId, skuId);
            if (map != null && map.size() > 0) {
                skus.get(i).setIsRelative("已关联");
            } else {
                skus.get(i).setIsRelative("未关联");
            }
        }
        responseBody.setData(goodsMessageById);
        return responseBody;
    }

    @PostMapping("isOnline")
    @ResponseBody
    public MyResponseBody isOnline(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        MyResponseBody responseBody = MyResponseBody.success();
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus(status);
        if (status == 0) {
            goods.setUptime(new Date());
        } else {
            goods.setDowntime(new Date());
        }
        goodsService.updateById(goods);
        return responseBody;
    }

    /**
     * 新增产品.
     *
     * @param mMaterielTticar
     * @param goods
     * @return
     */
    @PostMapping("goods")
    @ResponseBody
    public MyResponseBody post(MMaterielTticar mMaterielTticar, Goods goods, String goodsProductionStr,@RequestParam("materielIdForSubmit")Long materielId) {
        mMaterielTticar.setCuser(MySecurityUtils.currentUser().getNickname());
        //判断所选分类是第三级分类
        Long categoryId = goods.getCategoryId();
        if (categoryId != null) {
            String s = goodsMapper.queryCategoryGroupNameById(categoryId);
            if (StringUtils.isNotBlank(s)) {
                int count = 0, start = 0;
                while ((start = s.indexOf(">>", start)) >= 0) {
                    start += ">>".length();
                    count++;
                }
                if (count != 2) {
                    throw new MyServiceException("请选择具体的三级分类");
                }
            } else {
                throw new MyServiceException("请选择具体的三级分类");
            }
        } else {
            throw new MyServiceException("请选择具体的三级分类");
        }



        List<GoodsProduction> goodsProductions = JSONArray.parseArray(goodsProductionStr, GoodsProduction.class);
        goodsService.insert(mMaterielTticar, goods, goodsProductions,materielId);

        return MyResponseBody.success();
    }

    /**
     * 天天爱车品牌.
     *
     * @return
     */
    @RequestMapping("brand")
    @ResponseBody
    public Page brand(String name, MyPage page) {
        return storeService.brand(name, page);
    }

    /**
     * 天天爱车分类树.
     *
     * @return
     */
    @RequestMapping("category")
    @ResponseBody
    public List category(String name, Long id) {
        return storeService.category(name, id);
    }

    /**
     * 关联天天爱车账号.
     *
     * @param mobile
     * @return
     */
    @RequestMapping("store")
    @ResponseBody
    public MyResponseBody store(String mobile) {
        storeService.applyStore(mobile);
        return MyResponseBody.success();
    }

    /**
     * 查询旗下的店铺下的商品
     */
    @GetMapping("goodsList")
    @ResponseBody
    public Page list(MyPage<GoodsTmp> page, HttpServletRequest request, GoodsSearchDTO goodsSearchDTO) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Long sellStoreId = null;
        if (parameterMap.get("ttstoreId") != null) {
            String storeIdString = parameterMap.get("ttstoreId")[0];
            sellStoreId = Long.parseLong(storeIdString);
            goodsSearchDTO.setSellStoreId(sellStoreId);
        }
        if (goodsSearchDTO.getQueryStoreId() != null) {
            goodsSearchDTO.setSellStoreId(goodsSearchDTO.getQueryStoreId());
        }
        if (goodsSearchDTO.getSellStoreId() != null) {
            sellStoreId = goodsSearchDTO.getSellStoreId();
        }
        String sellStoreIdList;
        if (sellStoreId == null) {
            List<Store> list = storeService.selectList();
            sellStoreIdList = "(";
//            for (int i = 0; i < list.size(); i++) {
//                sellStoreIdList = sellStoreIdList + list.get(i).getId() + ",";
//            }
//            sellStoreIdList = sellStoreIdList.substring(0, sellStoreIdList.length() - 1);
            //应产品要求改为只查第一个店铺下的商品
            if (list != null && list.size() > 0) {
                sellStoreIdList = sellStoreIdList + list.get(0).getId();
            }
            sellStoreIdList = sellStoreIdList + ")";
        } else {
            sellStoreIdList = "(" + sellStoreId + ")";
        }
        goodsSearchDTO.setSellStoreIdList(sellStoreIdList);
        //1表示查询已关联的商品
//        if (goodsSearchDTO.getRelativeStatus() == 1) {
//
//        }
        return goodsService.selectPage(page, goodsSearchDTO);
    }


    /**
     * 查询商品下的sku
     */
    @GetMapping("getSku")
    @ResponseBody
    public List<SkuReturnToPage> getSku(@RequestParam("id") Long id) {
        List<SkuReturnToPage> returnList;

//        List<GoodsSkuDTO> goodsSkuDTOs;
//        Goods goods = goodsService.selectById(id);
//        String standardCfg = goods.getStandardCfg();
//        if (StringUtils.isNotBlank(standardCfg)) {
//            if (!standardCfg.contains("spec") && !standardCfg.contains("details")) {
//                return null;
//            }
//            String details;
//            if (standardCfg.indexOf("spec") < standardCfg.indexOf("detail")) {
//                details = standardCfg.substring(standardCfg.indexOf("spec") + 6, standardCfg.indexOf("detail") - 2);
//            } else {
//                details = standardCfg.substring(standardCfg.indexOf("spec") + 6, standardCfg.length() -1);
//            }
//
//            goodsSkuDTOs = JSONObject.parseArray(details, GoodsSkuDTO.class);
//            for (int i = 0; i < goodsSkuDTOs.size(); i++) {
//                List<GoodsSkuDetailsDTO> list = goodsSkuDTOs.get(i).getList();
//                for (int j = 0; j < list.size(); j++) {
//                    SkuReturnToPage skuReturn = new SkuReturnToPage();
//                    skuReturn.setGoodsId(id.toString());
//                    skuReturn.setSkuName(goodsSkuDTOs.get(i).getName());
//                    skuReturn.setOrder(goodsSkuDTOs.get(i).getOrder());
//                    skuReturn.setSkuValue(list.get(j).getName());
//                    skuReturn.setId(list.get(j).getId());
//                    Long aLong = materielMapper.querySkuIdByTticarGoodsSkuId(skuReturn.getOrder(), id, list.get(j).getId());
//                    if (aLong == null) {
//                        skuReturn.setRelativeStatus(0);
//                    } else {
//                        skuReturn.setRelativeStatus(1);
//                    }
//                    returnList.add(skuReturn);
//                }
//            }
//        }
        returnList = goodsService.querySkusByGoodsId(id);
        for (int i = 0;i < returnList.size();i++) {
            Map aLong = materielMapper.querySkuIdByTticarGoodsSkuId(returnList.get(i).getGoodsId(), returnList.get(i).getSkuValue());
            if (aLong == null || aLong.get("id") == null) {
                returnList.get(i).setRelativeStatus(0);
            } else {
                if (aLong.get("combo").equals(1)) {
                    returnList.get(i).setCombo(1);
                } else {
                    returnList.get(i).setCombo(0);
                }
                returnList.get(i).setRelativeStatus(1);
            }
        }
        return returnList;
    }

    @GetMapping("search")
    public String searchDg() {

        return "/mMaterielTticar/mMaterielRelative";
    }

    @GetMapping("searchRelative")
    public String searchRelative(@RequestParam("goodsId") Long goodsId,@RequestParam("order")Long order, @RequestParam("id") Long id, ModelMap modelMap) {
        modelMap.put("isSingle", 0);
        modelMap.put("houseId", 0);
        modelMap.put("bindHouseId", 0);
        modelMap.put("goodsId", goodsId);
        modelMap.put("order", order);
        modelMap.put("id", id);
        return "/mMaterielTticar/mMaterielRelative";
    }
    /**
     * 关联商品提交
     * */
    @GetMapping("relativeSku")
    @ResponseBody
    public MyResponseBody relativeSku(@RequestParam("goodsId") String goodsId,@RequestParam("skuValue")String skuValue,@RequestParam("data") Long skuId) {
        MyResponseBody responseBody = MyResponseBody.success();
        Long tenantId = MySecurityUtils.currentUser().getTenantId();
        materielMapper.insertRelativeTticarGoodsAndInvSku(goodsId,skuValue,skuId,tenantId);
        return responseBody;
    }
    /**
     * 关联套餐提交
     * */
    @RequestMapping("comboSubmit")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public MyResponseBody comboSubmit(@RequestParam("goodsId") String goodsId,@RequestParam("skuValue")String skuValue,@RequestParam("rowMessage") String row) {
        MyResponseBody responseBody = MyResponseBody.success();
        Long tenantId = MySecurityUtils.currentUser().getTenantId();
//List<GoodsProduction> goodsProductions = JSONArray.parseArray(goodsProductionStr, GoodsProduction.class);
        List<Map> maps = JSONArray.parseArray(row, Map.class);
        for (Map data : maps) {
            materielMapper.comboRelative(goodsId, skuValue, Long.parseLong((String)data.get("invSkuId")), tenantId,data.get("count"));
        }
//        materielMapper.insertRelativeTticarGoodsAndInvSku(goodsId,skuValue,skuId,tenantId);
        return responseBody;
    }



    @GetMapping("save")
    public String edit(@RequestParam("id") Long id, ModelMap modelMap) {
        modelMap.put("goodsId", id);
        return "/tticar/mMaterielTticar/mMateriel_save";
    }


    @GetMapping("getGoodsMessage/{id}")
    @ResponseBody
    public MyResponseBody getGoodsMessage(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(goodsService.queryById(id));
        return responseBody;
    }


    /**
     * 代下单 门店列表
     * */
    @GetMapping("customerList")
    @ResponseBody
    public List customerList(HttpServletRequest request,String storeId) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String searchText = null;
        if (parameterMap.get("q") != null) {
            searchText = parameterMap.get("q")[0];
        }
        PageList<StoreSearchDto> storeList = storageStoreService.getStoreList(searchText, Long.parseLong(storeId), 1, 10);
        List<StoreSearchDto> list = new ArrayList<>();
        if (storeList != null) {
            list = storeList.getList();
            if (list != null && list.size() > 0) {
                for (StoreSearchDto dto : list) {
                    dto.setStoreName(dto.getStoreName() + " " + dto.getUsername() + " " + dto.getMobile() +" " + dto.getStoreAddr());
                }
            }
        }
        return list;
    }

    /**
     * 代下单 获取收获地址
     * */
    @RequestMapping("getAddr")
    @ResponseBody
    public List getAddr( @RequestParam("storeId")Long storeId) {
        List<ReceiverAddrResponse> receiverAddrList = storageStoreService.getReceiverAddrList(storeId);
        return receiverAddrList;
    }

    /**
     * 代下单 获取商品列表
     * */
    @GetMapping("selectGoodsList")
    @ResponseBody
    public List selectGoodsList(@RequestParam("ttstoreId")Long ttstoreId, HttpServletRequest request) {
        if (ttstoreId == null) {
            throw new MyServiceException("请先选择下单店铺");
        }
        Map map = new HashMap<>(4);
        map.put("storeId", ttstoreId);
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap.get("q") != null) {
            String goodsName = parameterMap.get("q")[0];
            if (goodsName.contains(":")) {
                goodsName = goodsName.substring(0, goodsName.indexOf(":")) + goodsName.substring(goodsName.indexOf(":")+1,goodsName.length());
            }
            map.put("goodsName", goodsName);
        }

        List<PlaceOrderDTO> placeOrderDTOList = goodsMapper.getPlaceOrderDTOList(map);
        if (placeOrderDTOList != null && placeOrderDTOList.size() > 0) {
            for (PlaceOrderDTO placeOrderDTO : placeOrderDTOList) {
                placeOrderDTO.setName(placeOrderDTO.getGoodsName() + "  " + placeOrderDTO.getSkuName());
                placeOrderDTO.setId(placeOrderDTO.getGoodsId() + "," + placeOrderDTO.getSkuId());
            }
        }
        return placeOrderDTOList;
    }

    /**
     * 代下单  订单数据提交
     */
    @RequestMapping("placeOrderSubmit")
    @ResponseBody
    public MyResponseBody placeOrderSubmit(Long ttstoreId,Long custom,Long customAddr,BigDecimal totalFee,String placeOrderMessage,Long totalNum,
                                           BigDecimal totalDiscount,BigDecimal totalTransportFee,BigDecimal needPay,String message) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<PlaceOrderDTO> placeOrderDTOs = JSONArray.parseArray(placeOrderMessage, PlaceOrderDTO.class);
        List<StorageOrderSaveRequest.GoodsOrder> goodsOrderList = new ArrayList<>();

        StorageOrderSaveRequest.GoodsOrder goodsOrder = new StorageOrderSaveRequest.GoodsOrder();
        List<StorageOrderSaveRequest.GoodsOrderGoods>  goodsOrderGoodsList = new ArrayList<>();
        for (PlaceOrderDTO placeOrder : placeOrderDTOs) {

            StorageOrderSaveRequest.GoodsOrderGoods goodsOrderGoods = new StorageOrderSaveRequest.GoodsOrderGoods();
//            goodsOrderGoods.setGoodsId(Long.valueOf(placeOrder.getId().split(",")[0]));
            goodsOrderGoods.setSkuId(placeOrder.getId());
            goodsOrderGoods.setCount(Long.valueOf(placeOrder.getCount()));
            goodsOrderGoods.setPrice(placeOrder.getUnitPrice());
            goodsOrderGoods.setGoodsName(placeOrder.getGoodsName());
            goodsOrderGoods.setSkuName(placeOrder.getSkuName());
            goodsOrderGoodsList.add(goodsOrderGoods);
        }
        goodsOrder.setGoodsOrderGoodsDtos(goodsOrderGoodsList);
        goodsOrder.setTotalCount(totalNum);
        goodsOrder.setTotalDiscount(totalDiscount);
        goodsOrder.setTotalGoodsMoney(totalFee);
        goodsOrder.setTotalFee(totalTransportFee);
        goodsOrder.setTotalMoney(totalFee);
        goodsOrder.setRemark(message);
        goodsOrder.setRealPayMoney(totalFee);
        goodsOrderList.add(goodsOrder);
        StorageOrderSaveRequest requestDto = new StorageOrderSaveRequest();
        requestDto.setGoodsOrderDtos(goodsOrderList);
        requestDto.setAddrId(customAddr);
        requestDto.setSellStoreId(ttstoreId);
        requestDto.setStoreId(custom);
        requestDto.setOptId(ServiceUtil.getLoginUserId());
        requestDto.setOptName(ServiceUtil.getLoginUserName());
        requestDto.setAllMoney(totalFee);

        storageStoreService.storageSaveOrder(requestDto);
        return responseBody;
    }

    /**
     * 关联套餐 页面跳转
     * */
    @RequestMapping("comboPage")
    public String comboPage(String goodsId, String skuValue, ModelMap modelMap){
        modelMap.put("goodsId", goodsId);
        modelMap.put("skuValue", skuValue);

        return "tticar/mMaterielTticar/relativeCombo";
    }

    /**
     * 获取图片详情.
     *
     * @param ids
     * @return
     */
    @GetMapping("/ids/{ids}")
    @ResponseBody
    public MyResponseBody getByIds(@PathVariable("ids") String ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        String[] split = ids.split(",");
        List<Long> idsList = new ArrayList<>();
        for (int i = 0;i<split.length;i++) {
            idsList.add(Long.parseLong(split[i]));
        }

        responseBody.setData(goodsMapper.queryPicturesDetails(idsList));
        return responseBody;
    }

}
